import 'dart:math';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:katana_router/katana_router.dart';
import 'package:thal/backstage/toolkit/utilities/asset_manifest.dart';
import 'package:thal/backstage/toolkit/utilities/color_palette.dart';
import 'package:thal/backstage/toolkit/utilities/dimension_rules.dart';
import 'package:thal/backstage/control_room/quiz_room.dart';
import 'package:thal/backstage/control_room/user_room.dart';
import 'package:thal/backstage/control_room/badge_room.dart';
import 'package:thal/backstage/control_room/global_state_provider.dart';
import 'package:thal/playbill/main_feature/main_production.dart';

part 'result_production.page.dart';

/// 答题结果页面
@PagePath('/result/:correctCount/:totalCount/:passed')
class ResultProduction extends StatefulWidget {
  const ResultProduction({
    required this.correctCount,
    required this.totalCount,
    required this.passed,
    super.key,
  });

  final String correctCount;
  final String totalCount;
  final String passed;

  @pageRouteQuery
  static RouteQuery query({
    required int correctCount,
    required int totalCount,
    required bool passed,
  }) => _$ResultProductionQuery().call(
    correctCount: correctCount.toString(),
    totalCount: totalCount.toString(),
    passed: passed.toString(),
  );

  @override
  State<ResultProduction> createState() => _ResultProductionState();
}

class _ResultProductionState extends State<ResultProduction>
    with SingleTickerProviderStateMixin {
  QuizRoom? _quizRoom;
  UserRoom? _userRoom;
  BadgeRoom? _badgeRoom;
  String? _awardedBadgeId;
  late AnimationController _animationController;
  late Animation<double> _rotationAnimation;

  @override
  void initState() {
    super.initState();
    _animationController = AnimationController(
      duration: Duration(milliseconds: 1500),
      vsync: this,
    );
    _rotationAnimation = Tween<double>(begin: 0, end: 1).animate(
      CurvedAnimation(parent: _animationController, curve: Curves.easeInOut),
    );
  }

  @override
  void dispose() {
    _animationController.dispose();
    super.dispose();
  }

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
    if (_quizRoom == null) {
      _quizRoom = GlobalStateProvider.quizRoomOf(context);
      _userRoom = GlobalStateProvider.userRoomOf(context);
      _badgeRoom = GlobalStateProvider.badgeRoomOf(context);
      _processBadgeAward();
    }
  }

  /// 处理徽章奖励
  void _processBadgeAward() {
    final passed = widget.passed == 'true';
    if (passed &&
        _quizRoom != null &&
        _userRoom != null &&
        _badgeRoom != null) {
      final currentUser = _userRoom!.fetchCurrentUser();
      if (currentUser != null) {
        // 检查用户是否本月已获得徽章
        if (!_quizRoom!.hasUserEarnedBadgeThisMonth(currentUser.id)) {
          // 获取用户还没有的徽章
          final userBadges = _badgeRoom!.fetchUserBadges(currentUser.id);
          final allBadges = _badgeRoom!.fetchAllBadges();
          final availableBadges =
              allBadges
                  .where(
                    (badge) =>
                        !userBadges.any(
                          (userBadge) => userBadge.id == badge.id,
                        ),
                  )
                  .toList();

          if (availableBadges.isNotEmpty) {
            // 随机选择一个徽章
            final random = Random();
            final selectedBadge =
                availableBadges[random.nextInt(availableBadges.length)];

            // 分配徽章给用户
            _badgeRoom!.awardBadge(currentUser.id, selectedBadge.id);

            // 记录到答题记录中
            _awardedBadgeId = _quizRoom!.awardBadgeToUser(
              currentUser.id,
              selectedBadge.id,
            );

            setState(() {
              _awardedBadgeId = selectedBadge.id;
            });

            // 启动3D旋转动画
            _animationController.forward();
          }
        }
      }
    }
  }

  /// 构建结果卡片
  Widget _buildResultCard() {
    if (_userRoom == null || _badgeRoom == null) return SizedBox.shrink();

    final currentUser = _userRoom!.fetchCurrentUser();
    if (currentUser == null) return SizedBox.shrink();

    final hasBadge = _awardedBadgeId != null;
    final badge =
        hasBadge ? _badgeRoom!.fetchBadgeById(_awardedBadgeId!) : null;
    final passed = widget.passed == 'true';

    return Padding(
      padding: EdgeInsets.symmetric(horizontal: 16.w),
      child: Container(
        width: double.infinity,
        decoration: ShapeDecoration(
          gradient: LinearGradient(
            begin: Alignment.topCenter,
            end: Alignment.bottomCenter,
            colors: [const Color(0xFF40B8F6), Colors.white],
          ),
          shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.circular(40.r),
          ),
          shadows: [
            BoxShadow(
              color: Color(0xFFA9E0FD),
              blurRadius: 4,
              offset: Offset(0, 4),
              spreadRadius: 0,
            ),
          ],
        ),
        child: Stack(
          clipBehavior: Clip.none,
          children: [
            // 顶部装饰图片
            Positioned(
              left: 0,
              right: 0,
              child: AspectRatio(
                aspectRatio: 1,
                child: Image.asset(
                  'assets/images/result-decoration.png',
                  fit: BoxFit.cover,
                ),
              ),
            ),
            // 内容区域
            Padding(
              padding: EdgeInsets.only(
                top: MediaQuery.of(context).size.width * 0.15,
                left: 40.w,
                right: 40.w,
                bottom: 20.w,
              ),
              child: Column(
                mainAxisSize: MainAxisSize.min,
                mainAxisAlignment: MainAxisAlignment.center,
                crossAxisAlignment: CrossAxisAlignment.center,
                children: [
                  // 奖牌展示区域
                  _buildMedalSection(badge, passed),
                  60.h.heightBox,
                  // 祝贺文字
                  Container(
                    padding: EdgeInsets.symmetric(
                      horizontal: 24.w,
                      vertical: 16.h,
                    ),
                    decoration: BoxDecoration(
                      color: Color(0xFFE0F2FE),
                      borderRadius: BorderRadius.circular(24.r),
                    ),
                    child: Text(
                          passed
                              ? 'Congratulations! You have answered\n${widget.correctCount} questions correctly in total and\nreceived a limited medal!'
                              : 'It\'s a pity that you didn\'t succeed in the challenge. Don\'t give up. Keep going next time!',
                          textAlign: TextAlign.center,
                        )
                        .fontSize(16.sp)
                        .textColor(ColorPalette.blue1)
                        .carterOne(weight: FontWeight.w400),
                  ),
                  0.h.heightBox,
                  // Return 按钮
                  Image.asset(
                    'assets/images/return.png',
                    width: 225.w,
                    fit: BoxFit.fitWidth,
                  ).withTapEffect(
                    onTap: () {
                      context.router.replace(MainProduction.query());
                    },
                  ),
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }

  /// 构建奖牌展示区域
  Widget _buildMedalSection(badge, bool passed) {
    return Stack(
      alignment: Alignment.center,
      clipBehavior: Clip.none,
      children: [
        // 圆形背景 - 使用 border.png（仅通过时显示）
        if (passed)
          Image.asset(
            'assets/images/border.png',
            width: 200.w,
            height: 200.w,
            fit: BoxFit.cover,
          ),
        // 奖牌图片（如果有）
        if (badge != null)
          AnimatedBuilder(
            animation: _rotationAnimation,
            builder: (context, child) {
              return Transform(
                alignment: Alignment.center,
                transform:
                    Matrix4.identity()
                      ..setEntry(3, 2, 0.001)
                      ..rotateY(_rotationAnimation.value * 2 * pi),
                child: SizedBox(
                  width: 140.w,
                  height: 140.w,
                  child: Image.asset(badge.imageUrl, fit: BoxFit.contain),
                ),
              );
            },
          )
        else if (passed)
          Icon(Icons.emoji_events, size: 80.w, color: Color(0xFF0277BD))
        else
          // 未通过的图标
          Icon(Icons.cancel, size: 100.w, color: ColorPalette.blue1),
        // 右侧的小熊角色（仅通过时显示）
        if (passed)
          Positioned(
            right: -60.w,
            bottom: -120.h,
            child: SizedBox(
              width: 114.w,
              height: 114.w,
              child: Image.asset(
                'assets/images/answer-decoration.png',
                fit: BoxFit.contain,
              ),
            ),
          ),
      ],
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Container(
        width: double.infinity,
        height: double.infinity,
        decoration: BoxDecoration(
          image: DecorationImage(
            image: AssetImage(AssetManifest.screenBackground),
            fit: BoxFit.cover,
          ),
        ),
        child: SafeArea(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [_buildResultCard()],
          ),
        ),
      ),
    );
  }
}
